package com.example.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.constant.RedisConstance;
import com.example.entity.ExamStore;
import com.example.entity.Spu;
import com.example.entity.Store;
import com.example.entity.User;
import com.example.mapper.*;
import com.example.service.StoreService;
import com.example.util.RedisUtil;
import com.example.vo.IdHolder;
import com.example.vo.Result;
import com.example.vo.SpuItemVo;
import com.example.vo.buyer.StoreDetailVo;
import com.example.vo.buyer.StoreVo;
import com.example.vo.comment.PageResult;
import io.jsonwebtoken.lang.Objects;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @Author: aimi
 * @Create: 2024-05-30
 **/
@Service
@Slf4j
public class StoreServiceImpl extends ServiceImpl<StoreMapper, Store>
        implements StoreService {

    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private SkuMapper skuMapper;
    @Resource
    private ExamStoreMapper examStoreMapper;
    @Resource
    private UserMapper userMapper;

    @Override
    public StoreDetailVo getStoreDetail(Long storeId) {
        String key = RedisConstance.STORE_PREFIX+storeId;
        Object o = redisUtil.get(key);
        if(!Objects.isEmpty(o)){
            String detailStr = o.toString();
            return JSON.parseObject(detailStr,StoreDetailVo.class);
        }
        Store store = storeMapper.selectById(storeId);
        if(store == null){
            return null;
        }
        StoreVo storeVo = new StoreVo();
        BeanUtils.copyProperties(store,storeVo);

        QueryWrapper<Spu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id",storeId);
        List<Spu> spuList = spuMapper.selectList(queryWrapper);
        ArrayList<SpuItemVo> spuItemVos = new ArrayList<>();
        spuList.forEach(spu -> {
            Long spuId = spu.getId();
            BigDecimal minPrice = skuMapper.getMinPrice(Math.toIntExact(spuId));
            String defaultImage = skuMapper.getDefaultImageBySpuId(Math.toIntExact(spuId));

            SpuItemVo spuItemVo = new SpuItemVo();
            BeanUtils.copyProperties(spu,spuItemVo);
            spuItemVo.setPrice(minPrice);
            spuItemVo.setImage(defaultImage);
            spuItemVos.add(spuItemVo);
        });
        StoreDetailVo storeDetailVo = new StoreDetailVo(storeVo,spuItemVos);
        redisUtil.set(key,JSON.toJSONString(storeDetailVo),RedisConstance.STORE_EXPIRE_TIME * 60);
        return storeDetailVo;
    }

    @Transactional
    @Override
    public void downAllGoods(Long storeId) {
        Store store = storeMapper.selectById(storeId);
        if(store != null){
            QueryWrapper<Spu> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("store_id",storeId);
            boolean downStatus = !store.getDownAllStatus();
            List<Spu> spus = spuMapper.selectList(queryWrapper);
            spus.forEach(spu -> {
                spu.setPublishStatus(downStatus ? 0 : 1);
                spuMapper.updateById(spu);
            });
            store.setDownAllStatus(downStatus);
            storeMapper.updateById(store);
        }
    }

    @Override
    public PageResult<ExamStore> getExamStoreList(Integer pageNo, Integer pageSize, Integer status) {
        Page<ExamStore> page = new Page<>(pageNo, pageSize);
        IPage<ExamStore> examStorePage = examStoreMapper.selectPage(page, new QueryWrapper<ExamStore>().eq("status", status));
        long total = examStorePage.getTotal();
        List<ExamStore> records = examStorePage.getRecords();
        return new PageResult<>(total, records);
    }

    @Override
    @Transactional
    public void examStatus(Long examId, Integer status) {
        ExamStore examStore = examStoreMapper.selectById(examId);
        examStore.setStatus(status);
        //System.out.println("examStore = " + examStore);
        examStoreMapper.updateById(examStore);
        Store store = new Store();
        BeanUtils.copyProperties(examStore,store);
        //设置默认值
        store.setId(null);
        store.setGoodsNum(0);
        store.setCollectNum(0);
        store.setDownAllStatus(false);
        store.setDeleteFlag(false);
        store.setSelfOperated(false);
        //System.out.println("store = " + store);
        storeMapper.insert(store);

        //更新店铺主账号信息
        User user = userMapper.selectById(store.getUserId());
        user.setHaveStore(true);
        user.setStoreId(store.getId());
        userMapper.updateById(user);
    }

    @Override
    public void storeEntry(ExamStore examStore) {
        Long userId = IdHolder.getUserId();
        examStore.setUserId(userId);
        examStore.setCreateTime(LocalDateTime.now());
        examStore.setStatus(0);
        examStoreMapper.insert(examStore);
    }


    @Override
    public Store getByUserId(Long userId) {
        LambdaQueryWrapper<Store> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Store::getUserId, userId);

        return storeMapper.selectOne(queryWrapper);
    }


    @Override
    public String getStoreNameById(Long storeId) {
        return storeMapper.getStoreNameById(storeId);
    }



    @Override
    public Result<Long> fetchUserIdByStoreId(Long storeId) {
        Long userId = baseMapper.fetchUserIdByStoreId(storeId);
        return Result.ok(userId);
    }
}